package com.sugon.service;

import com.sugon.Application;
import com.sugon.util.FfmpegThread;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.UUID;


/**
 * @description:
 * @author: jichenglu
 * @create: 2019-09-02 14:56
 **/
@Service
public class VideoService {

    @Value("${ffmpeg.rtmpUrl}")
    private String rtmpUrl;

    @Value("${ffmpeg.ffmpegPath}")
    private String ffmpegPath;

    @Value("${ffmpeg.display}")
    private String display;

    @Value("${ffmpeg.flvUrl}")
    private String flvUrl;

    @Value("${ffmpeg.playtime}")
    private long playTime;

    public String getRtmpUrl(String rtspUrl) throws Exception {

        String key = UUID.randomUUID().toString().replace("-", "");
        FfmpegThread ffmpegThread = new FfmpegThread(key, rtspUrl, rtmpUrl, ffmpegPath,display,playTime);
        ffmpegThread.setName(key);
        ffmpegThread.start();
//        System.out.println("生成rtmp:" + rtmpUrl + key);
        return flvUrl + key;
    }

    public int stopFfmpeg(String key) {
        int k = 1;
        ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
        int noThreads = currentGroup.activeCount();
        Thread[] lstThreads = new Thread[noThreads];
        currentGroup.enumerate(lstThreads);
        for (int i = 0; i < noThreads; i++) {
            String nm = lstThreads[i].getName();
            if (nm.equals(key)) {
                Application.processMap.get(key).destroy();
                Application.processMap.remove(key);
                lstThreads[i].interrupt();
                System.out.println("关闭线程号：" + i + " = " + nm);
                k = 0;
                break;
            }
        }
        return k;
    }

    /**
     * 每8小时释放转码资源
     */
    @Scheduled(cron = "0 0 0/8 * * ? ")
    public void task(){
        Application.urlMap.entrySet().stream().map(x -> x.getValue())
                .forEach(x -> {
                    String[] strs = x.split("/");
                    String str = strs[strs.length-1];
                    stopFfmpeg(str);
                });
        Application.urlMap.clear();
    }

}
